<?php

namespace ApiBundle\Controller\User;


use ApiBundle\Controller\BaseController;
use Helper\Validations;
use Symfony\Component\HttpFoundation\Request;

class AuthController extends BaseController
{

    /**
     * 登录
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function loginAction(Request $request)
    {

        // TODO 1:  获取数据
        $phone = $request->get("phone");
        $password = $request ->get("password");

        // TODO 2: 验证

        $validations = $this->get("helper.validations");
        if(!$validations->isMobile($phone) || !$validations->isPassword($password))
        {
            return $this->jsonResponse(1,"手机号或密码格式不正确");
        }

        // TODO 3: 数据库操作
        $conn = $this->get("database_connection");
        $user = $conn->fetchAssoc("SELECT * FROM user WHERE phone = '". $phone ."'");

        if($user === false){
            return $this->jsonResponse("2","当前手机号尚未注册");
        }
        $password = sha1(md5($password). $user['salt']);

        if($user['password'] != $password)
        {
            return $this->jsonResponse(3,"手机号与密码不匹配");
        }

        if($user['status'] == 0){
            return $this->jsonResponse(1,"帐号已被禁用");
        }


        $this->get('session')->set('user_id', $user['id']);
        $this->get('session')->set('phone', $user['phone']);

        $token_value = $this->get("helper.strings")->generateToken($phone);
        $conn->update("user",array("token" => $token_value),array("id" => $user['id']));

        $data = $conn->fetchAssoc("SELECT * FROM user WHERE id = '". $user['id'] ."'");

        // TODO 4.返回值
        return $this->jsonResponse(0,"登录成功",$data);

    }

    /**
     * 退出登录
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function logoutAction(Request $request)
    {
        $conn = $this->get('database_connection');
        $token = $request->get("token");

        if($this->isLogged($conn)){

            $conn->update("user",array("token" => NULL), array("token" => $token));
        }
        $this->get("session")->clear();
        return $this->jsonResponse(0,"退出成功");

    }

    /*
     * 注册  无名片注册
     */
    public function registerAction(Request $request){

        $phone = $request -> get("phone");
        $name = $request -> get("name");
        $company = $request -> get("company");
        $position = $request -> get("position");

        $validation_code = $request ->get('validation_code');
        $password = $request -> get("password");
        $comfire_password = $request -> get("comfirm_password");


        // TODO 1: 验证
        $validations = $this->get("helper.validations");
        $serviceStrings = $this->get("helper.strings");

        if(empty($phone) || empty($name) || empty($company) || empty($position) || empty($validation_code) || empty($password)){
            return $this->jsonResponse(1,"参数错误");
        }

        if(!$phone || !$validations->isMobile($phone))
        {
            return $this->jsonResponse(1,"手机号格式不正确");
        }

        // TODO : 短信验证
        $message_error = $this->checkSMSSalt($phone, $validation_code, 1, 1);
        if($message_error){
            return $this->jsonResponse(1,$message_error);
        }

        if(!$password || !$validations->isPassword($password))
        {
            return $this->jsonResponse(1,"密码为6~18位");
        }

        if(!$comfire_password || $comfire_password != $password){
            return $this->jsonResponse(1,"确认密码与密码不统一");
        }



        // 姓名验证
        $name_length = mb_strlen($name, "utf8");
        if($name_length > 15 || $name_length < 2)
        {
            return $this->jsonResponse(1,"姓名长度在2~15之间");
        }

        $posi_length = mb_strlen($position,"utf8");
        if($posi_length > 15 || $posi_length < 2)
        {
            return $this->jsonResponse(1,"职位长度在2~15之间");
        }


        // 判断手机号是否存在
        $conn = $this->get("database_connection");

        if($this->checkPhoneExit($phone)){
            return $this->jsonResponse(3,"该联络人已存在");
        }

        // TODO :  公司名称判断
        $is_company = $conn->fetchAssoc("SELECT * FROM company WHERE name = '". $company ."'");
        if(!$is_company){
            //return $this->jsonResponse(1,"企业不存在，用工商接口");

            // 工商接口
            $company_url = "http://v.juhe.cn/youshu/query?key=5f8549bbbbf5a201dd71e0ea4beeca56&name=". urlencode($company);

            $new_company = $this->curl($company_url);

            if($new_company->error_code == 0){

//                // 获取企业数据，插入数据库
                $conn->insert("company",$this->insertCompany($new_company));

                $new_company_id = $conn->lastInsertId();
                $new_company_address = $new_company->result->address;


                /*
                * TODO 商标查询
                */
                $pageSize = "10";
                $curr_page = "1";
                $mark_init_url = "http://japi.juhe.cn/trademark/search?key=48fc7d3240edf38df9daaebebbdc1218&keyword=". urlencode($company);
                $mark_url = $mark_init_url ."&pageSize=".$pageSize;
                $mark_url .="&pageNo=".$curr_page;

                $new_mark = $this->curl($mark_url);

                //var_dump($new_mark);exit;

                // 插入数据库 company表


                /*
                 * TODO 专利查询
                 */
                $next_page = "1";
                $page_size = "10";
                $patent_init_url = "http://v.juhe.cn/patent/search.php?key=85f7fe87ab8a171a0e8f307e4d5a6bf8&q=". urlencode($company);

                $patent_url = $patent_init_url . "&p=".$next_page;
                $patent_url = $patent_url . "&ps=".$page_size;


                $new_pant = $this->curl($patent_url);

                $patent_data = $new_pant->result->patents;

                //第一页 插入专利数据
                foreach ($patent_data as $item){
                    // 插入专利数据

                    $item2 = json_decode(json_encode($item),true);
                    $conn->insert("company_patent",$this->insertPatentArray($item2,$new_company_id));
                }

                // 查找下一页的专利 非第一页
                $page_next_page = $new_pant->result->nextPage;

                for($i=1;$i<$new_pant->result->totalPages;$i++){

                    if($page_next_page > 0){

                        $page_url = $patent_init_url . "&p=".$page_next_page. "&ps=".$page_size;
                        $page_new_pant = $this->curl($page_url);


                        $page_patent_data = $page_new_pant->result->patents;

                        $page_next_page = $page_new_pant->result->nextPage;


                        foreach ($page_patent_data as $item_a){

                            $item2 = json_decode(json_encode($item_a),true);

                            // 插入专利数据
                            $conn->insert("company_patent",$this->insertPatentArray($item2,$new_company_id));


                        }


                    }

                }



            } else {
                return $this->jsonResponse(1,"企业查询：".$new_company->reason);
            }

        } else {
            $new_company_id = $is_company['id'];
            $new_company_address = $is_company['address'];
        }

        $salt = $serviceStrings->generateSalt(6,true);
        $encryptPassword = $serviceStrings->encryptPassword($password,$salt);
        $created_at = date("Y-m-d H:i:s");

        $new_user = array(
            "phone" => $phone,
            "salt" => $salt,
            "password" => $encryptPassword,
            "name" => $name,
            "company_full_name" => $company,
            "position_name" => $position,
            "created_at" => $created_at,
            "company_id" => $new_company_id,
            "company_address" => $new_company_address
        );

        if($is_company){
            $new_user['district_id'] = $is_company['district_id'];
        }

        $result = $conn->insert("user",$new_user);

        if($result){
            return $this->jsonResponse(0,"注册成功");
        }
    }

    /*
     * 找回密码
     */
    public function forgetPasswordAction(Request $request)
    {
        $phone = $request->request->get("phone");
        $validation_code = $request->request->get("validation_code");
        $password = $request->request->get("password");
        $comfire_password = $request->request->get("comfire_password");

        $validations = $this->get("helper.validations");
        $serviceStrings = $this->get("helper.strings");

        if(!$phone || !$validations->isMobile($phone))
        {
            return $this->jsonResponse(1,"手机号格式不正确");
        }
        if(empty($validation_code)){
            return $this->jsonResponse(1,"请输入验证码");
        }

        if(!$password || !$validations->isPassword($password))
        {
            return $this->jsonResponse(2,"密码为6~18位");
        }

        if(!$comfire_password || $comfire_password != $password){
            return $this->jsonResponse(2,"确认密码与密码不统一");
        }
        $conn = $this->get("database_connection");

        // TODO : 短信验证
        $message_error = $this->checkSMSSalt($phone, $validation_code, 2, 1);
        if($message_error){
            return $this->jsonResponse(1,$message_error);
        }


        $select = $conn->fetchAssoc("SELECT * FROM user WHERE phone = '". $phone ."'");
        if(!$select){
            return $this->jsonResponse(1,"用户不存在");
        }
        $salt = $select['salt'];
        $encryptPassword = $serviceStrings->encryptPassword($password,$salt);
        $data = array(
            "password"=>$encryptPassword
        );
        $where = array(
            "phone"=>$phone
        );

        $update = $conn->update("user",$data,$where);


        return $this->jsonResponse(0,"找回密码成功",$update);


    }

    /*
     * 编辑用户信息
     */
    public function editUserMessageAction(Request $request)
    {
        // 邮箱，科技载体，
        $email = $request->get("email");
        $admin_id = $request->get("admin_id");
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        if(empty($email)){
            return $this->jsonResponse(1,"参数错误");
        }

        $validations = $this->get("helper.validations");
        if(!$validations->isEmail($email)){
            return $this->jsonResponse(2,"邮箱格式错误");
        }

        // 修改邮箱
        $data = array(
            "email" => $email
        );
        $conn->update("user",$data,array("id"=>$this->getUserId()));

        $user = $conn->fetchAssoc("SELECT * FROM user WHERE id = '". $this->getUserId() ."'");
        if($admin_id != ""){
            // 判断用户是否是科技联络人
            if($user['technology_liaisons_status'] != "1"){
                return $this->jsonResponse(1,"非科技联络人不可修改科技载体");
            }

            if($admin_id == "0"){
                $admin_id = null;
            }
            $conn->update("company",array("admin_id" => $admin_id),array("id" => $user['company_id']));
        }

        return $this->jsonResponse(0,"操作成功");
    }

    /*
     * 修改密码
     */
    public function updatePasswordAction(Request $request)
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }
        $password = $request->get("password");
        $new_password = $request->get("new_password");
        $comfirm_password = $request->get("comfirm_password");

        // TODO: 验证
        $validations = $this->get("helper.validations");
        $strings = $this->get("helper.strings");

        if(!$validations->isPassword($new_password)){
            return $this->jsonResponse(1,"密码为6~18位");
        }
        if($new_password != $comfirm_password){
            return $this->jsonResponse(1,"密码与确认密码不一致");
        }

        // TODO： 查询
        $user = $conn->fetchAssoc("SELECT * FROM user WHERE id = '". $this->getUserId() ."'");

        $password = $strings->encryptPassword($password,$user['salt']);

        // TODO: 原密码判断
        if($user['password'] != $password){
            return $this->jsonResponse(2,"原密码错误");
        }

        $encrypt_salt = $strings->generateSalt(6,true);
        $encrypt_password = $strings->encryptPassword($new_password,$encrypt_salt);

        $data = array(
            "password" => $encrypt_password,
            "salt" => $encrypt_salt
        );
        $conn->update("user",$data,array("id" => $user['id'] ));


        return $this->jsonResponse(0,"操作成功");
    }

    /*
     * 判断是否是科技联络人
     */
    public function judgeScienceContectAction()
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }
        $user = $conn->fetchAssoc("SELECT * FROM user WHERE id = '". $this->getUserId() ."'");
        if($user['technology_liaisons_status'] == '1'){
            return $this->jsonResponse(0,"科技联络人");
        } else {
            return $this->jsonResponse(1,"非科技联络人");
        }
    }

    /*
     * 申请科技联络人
     */
    public function applyScienceContectAction()
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $conn->update("user",array("technology_liaisons_status" => "0"),array("id" => $this->getUserId()));
        return $this->jsonResponse(0,"已申请，请等待管理员审核");
    }

    /*
     * 判断企业信息是否完善
     */
    public function judgeUserAction()
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $data = $conn->fetchAssoc("SELECT company_category_id FROM company WHERE id IN (SELECT company_id FROM user WHERE id = '". $this->getUserId() ."')");
        if($data['company_category_id'] == NULL){
            return $this->jsonResponse(0,"企业信息不完善",$data);
        } else {
            return $this->jsonResponse(1,"企业信息已完善，非第一个用户",$data);
        }
    }

    /*
     * 完善企业信息,完善用户自己的信息
     */
    public function setCompanyMessageAction(Request $request)
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $district_id = $request->get("district_id");

        $category_id = $request->get("category_id");
        $attribute_id = $request->get("attribute_id");
        $admin_id = $request->get("admin_id");

        if(empty($category_id) || empty($attribute_id) || empty($district_id)){
            return $this->jsonResponse(1,"企业属性,企业类别,所属区域不能为空");
        }

        $company_id = $conn->fetchAssoc("SELECT company_id FROM user WHERE id = '". $this->getUserId() ."'");

        // 完善企业信息
        $data = array(
            "company_attribute_id" => $attribute_id,
            "company_category_id" => $category_id,
            "district_id" => $district_id
        );

        if(!empty($admin_id)){
            $data['admin_id'] = $admin_id;
        }

        $conn->update("company",$data,array("id" => $company_id['company_id']));

        //完善用户信息
        $update_user = array(
            "district_id" => $district_id
        );

        $conn->update("user",$update_user,array("id" => $this->getUserId()));
        return $this->jsonResponse(0,"操作成功");

    }

    /*
     * 名片识别
     */
    public function cardRecognitionAction(Request $request)
    {
        $image = $request->get("image");

        //调用使用的方法
        //$img_dir = $this->container->get('kernel')->getRootDir() . '/../web/' . $image;
        $img_base64 = $this->base64EncodeImage($image);

        // 名片接口
        $url = "http://op.juhe.cn/hanvon/bcard/query";
        $post_data = array ("image" => $img_base64,"key" => "3c73b261c7c42ef84adeabfb8ba940a2");

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);

        $card_message = json_decode($output);


        if($card_message->error_code == 0){
            return $this->jsonResponse(0,$card_message->reason,array("data"=>$card_message));
        } else if($card_message->error_code == 213903) {

            return $this->jsonResponse(1,"名片识别错误");
        } else {
            return $this->jsonResponse(1,$card_message->reason);
        }

    }


    /*
     * 用户 banner显示
     */
    public function getUserBannerAction(){
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $data = $conn->fetchAll("SELECT * FROM banner WHERE is_company = 1 AND (district_id = (SELECT district_id FROM user WHERE id = '". $this->getUserId() ."') OR (admin_role_id = 1)  )");

        return $this->jsonResponse(0,"操作成功",$data);

    }

}
